< previous page page_494 next page >

Page 494
Saving, Opening, and Printing Documents
After creating a Word document in Visual Basic, you can use the Save and SaveAs methods of the document object to save it to disk. You should first use the SaveAs method to specify a filename:
objDoc.SaveAs "C:\Temp\MyDoc.Doc"
The Save method has no parameters; it is intended for saving a document after you have already specified a filename:
If objDoc.Saved = False then objDoc.Save
Note that you can use the Saved property to check whether a document has been saved since any changes were made.
note.gif If you use the Save method without first calling SaveAs, Word prompts the user for a filename. square.gif

To open an existing document, create an instance of the Word.Application object and use the Set statement with the Open of the Documents collection:
Set objDoc = objWord.Documents.Open ("C:\Temp\Junk.Doc")
In the preceding line of code, if the file JUNK.DOC does not exist, Word displays an error message. You can handle this situation yourself in Visual Basic by using an On Error statement and checking the document object to see whether the document was actually opened:
On Error Resume Next
Set objDoc = objWord.Documents.Open("C:\Temp\Junk.Doc")
If objDoc Is Nothing Then MsgBox "Open was not successful!"
To print in Word, use the PrintOut and PrintPreview methods. The following line of code causes Word to print a document:
objdoc.PrintOut
If you are creating a report in Word, you might want to use the PrintPreview method instead so that the user can view the report and decide whether to print it.
Working with Text
In Listing 22.1, you used the InsertAfter and InsertParagraphAfter methods to add text to a Word document. However, many additional ways are available for you to work with text in Word.
For example, you can use the Words collection to retrieve text a word at a time. The following code sample adds the words in a Word.Document object to a list box:
For nWord = 1 to objDoc.Words.Count
    lstWords.AddItem "Word " & nWord & " is " & objDoc.Words(nWord).Text
Next nWord

 
< previous page page_494 next page >